import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class NotificationRoute extends StatefulWidget {
  const NotificationRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _NotificationRouteState();
}

class _NotificationRouteState extends State<NotificationRoute> {
  final logger = Logger(printer: LogfmtPrinter());

  String _msg = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('通知 Notification'),
      ),
      body: NotificationListener<MyNotification>(
        onNotification: (n) {
          logger.i("message : ${n.msg}");
          return false;
        },
        child: NotificationListener<MyNotification>(
          onNotification: (n) {
            setState(() {
              _msg += n.msg + "  ";
            });
            return true;
          },
          child: Center(
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 10,
                ),
                Builder(
                  builder: (context) {
                    return ElevatedButton(
                      //按钮点击时分发通知
                      onPressed: () => MyNotification("Hi").dispatch(context),
                      child: const Text("Send Notification"),
                    );
                  },
                ),
                const SizedBox(
                  height: 50,
                ),
                Text(_msg)
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MyNotification extends Notification {
  final String msg;

  MyNotification(this.msg);
}
